package com.github.defense.plugin.gray.holder;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * @Author: lettger
 * @Date: 2021/6/7 3:09 下午
 */
@Configuration
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        assertApplicationContext();
        return applicationContext;
    }

    public static <T> T getBean(String beanName) {
        assertApplicationContext();
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> tClass) {
        assertApplicationContext();
        return applicationContext.getBean(tClass);
    }


    private static void assertApplicationContext() {
        if (SpringContextHolder.applicationContext == null) {
            throw new RuntimeException("ApplicationContext 为null;请检查是否注入了ApplicationContext");
        }
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> type) {
        assertApplicationContext();
        return applicationContext.getBeansOfType(type);
    }

    public static Environment getEnvironment(){
        assertApplicationContext();
        return applicationContext.getEnvironment();
    }
}
